import React, { Component } from 'react';
import GoBack from "@/components/TheGoBack";
import { apiGetGoodsClassifyTreeAll, apiGetBrandinfoList } from '@/request/mallManagement'
import { apiAppCouponInfoAdd, apiGetCouponByIdListView, apiAppCouponInfoEdit } from '@/request/couponManagement'

import {
  Select,
  Form,
  Input,
  Radio,
  InputNumber,
  DatePicker,
  Typography,
  Checkbox,
  Row,
  Col,
  Space,
  Button,
  TreeSelect
} from "antd";
import moment from 'moment';
import Goods from './components/Goods'
import TheButton from "@/components/TheButton";
import './style.scss'

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Title } = Typography;

let expiryDateStartStatus = true

class Add extends React.Component {
  constructor() {
    super();
    this.GoodsRef = React.createRef()
    this.state = {
      btnLoading: false,
      mode: '',
      couponId: '',
      goodsDefault: [],
      selectGoodsKeys: [],
      classifyTree: [],
      selectClassifyKeys: [],
      brandList: [],
      selectBrandKeys: [],
      initialValues: {
        couponSpecies: 'P',
        couponType: 'J',
        number: -1,
        usePrice: -1,
        commodityScope: 0,
        activityTime: 0,
        couponSourceDirect: 0,
        remindUser: 1,
        remindNumber: 1,
        activitySatisfy: 0,
        activityPresented: 1,
        couponSourceCard: 0
      },
      dataSource: {}
    }
  }

  componentDidMount = async () => {
    let { type, id } = this.props.match.params
    this.setState({
      mode: type,
      couponId: id
    })
    if (type !== 'create') {
      await this.getDetail(id)
    }
    await this.getGoodsClassifyTreeAll()
    await this.getBrandList()
  }

  // 获取详情回显
  getDetail = async (id) => {
    let res = await apiGetCouponByIdListView(id)
    if (res.code === 0 && res.data) {
      this.setState({
        dataSource: res.data
      })
      let params = this.dataFilter(res.data)
      // 活动时间 固定时间
      if (params.activityStartTime && params.activityStopTime) {
        params.activityTimeFixed = [params.activityStartTime, params.activityStopTime]
        delete params.activityStartTime
        delete params.activityStopTime
      }
      // 商品范围
      // if ('commodityScope' in params){
      //     if (params.commodityScope === 2){
      //         params.category = 4
      //     }
      // }
      // 券有效期 指定日期
      if (params.startTime && params.endTime) {
        params.expiryDateAppoint = [params.startTime, params.endTime]
        delete params.startTime
        delete params.endTime
        delete params.takeEffectTime
      } else if (params.takeEffectTime !== -1) {
        params.effectiveTimeTwo = params.effectiveTime
      } else {
        params.effectiveTimeOne = params.effectiveTime
        delete params.takeEffectTime
      }
      // 发放总量
      if ('couponStock' in params) {
        if (params.couponStock === -1) {
          params.number = -1
          delete params.couponStock
          delete params.couponStockCount
        } else {
          params.number = 2
        }
      }
      // 使用门槛
      if ("usePrice" in params) {
        if (params.usePrice !== -1) {
          params.usePriceNumber = params.usePrice
          params.usePrice = 2
        }
      }
      // 优惠金额
      if (params.couponMaxPrice !== -1) {
        params.specialDiscountCheckbox = 'yes'
      } else {
        delete params.couponMaxPrice
      }
      // 领取限制
      if (params.exchangeDays === -1 && params.exchangeCount === -1) {
        params.limitRadio = -1
        delete params.exchangeDays
      } else {
        if (params.exchangeDays !== -1) {
          params.limitRadio = 3
          params.exchangeCountTwo = params.exchangeCount
          delete params.exchangeCount
        } else {
          params.limitRadio = 2
          params.exchangeCountOne = params.exchangeCount
          delete params.exchangeCount
          delete params.exchangeDays
        }
      }
      // CDK关联
      if (params.cdkeyState) {
        delete params.cdkeyNum
      }
      // 口令
      if (params.passwordState) {
        delete params.passwordNum
      }
      if (params.dataType) {
        let { category, brands, classifyTypeList, goodsInfos } = params.dataType
        // 下级类别
        if (category) {
          params.category = category
        }
        // 类目
        if (classifyTypeList) {
          params.goodsCategory = classifyTypeList
          this.setState({
            selectClassifyKeys: classifyTypeList
          })
        }
        // 品牌
        if (brands) {
          params.goodsBrand = brands
          this.setState({
            selectBrandKeys: brands
          })
        }
        // 商品
        if (goodsInfos) {
          params.goodsInfoList = goodsInfos
          this.setState({
            selectGoodsKeys: goodsInfos.map(item => {
              return item.goodsId
            }),
            goodsDefault: goodsInfos
          })
        }
      }
      console.log(params)
      this.formRef.setFieldsValue({
        ...params
      })
    }
  }
  // 去除不使用的undefined字段
  dataFilter = (data) => {
    return Object.keys(data)
      .filter((key) => data[key] !== null && data[key] !== undefined)
      .reduce((acc, key) => ({ ...acc, [key]: data[key] }), {});
  }

  // 抓取表单验证失败提示
  onFinishFailed(values) {
    console.log(values, '抓取表单验证失败提示:onFinishFailed');
    if (values.errorFields.length > 0) {
      React.$message({
        type: 'warn',
        content: values.errorFields[0].errors[0]
      })
    }
  }

  //form表单确定事件
  onFinish = async (values) => {
    this.setState({
      btnLoading: true
    })
    let params = this.dataFilter(values)
    let { mode, couponId, dataSource } = this.state
    // 活动时间 固定时间
    if ('activityTimeFixed' in params) {
      params.activityStartTime = params.activityTimeFixed[0]
      params.activityStopTime = params.activityTimeFixed[1]
      delete params.activityTimeFixed
    }
    // 商品范围
    if ('commodityScope' in params) {
      if (params.commodityScope === 2) {
        params.category = 4
      }
    }
    // 券有效期 指定日期
    if ('timeType' in params) {
      if ('expiryDateAppoint' in params) {
        params.startTime = params.expiryDateAppoint[0]
        params.endTime = params.expiryDateAppoint[1]
        delete params.expiryDateAppoint
      }
      if (params.timeType === 1) {
        params.effectiveTime = params.effectiveTimeOne
        delete params.effectiveTimeOne
      }
      if (params.timeType === 2) {
        params.effectiveTime = params.effectiveTimeTwo
        delete params.effectiveTimeTwo
      }
    }
    // 发放总量
    if ('number' in params) {
      if (params.number === -1) {
        params.couponStock = -1
        params.couponStockCount = -1
      } else if (mode === 'edit') {
        params.couponStock = dataSource.couponStock
        if (dataSource.couponStockCount !== -1) {
          params.subStock = params.couponStockCount - dataSource.couponStockCount
        }
      } else {
        params.couponStock = params.couponStockCount
      }
      delete params.number
    }
    // 使用门槛
    if ("usePrice" in params) {
      if (params.usePrice === 2) {
        params.usePrice = params.usePriceNumber
        delete params.usePriceNumber
      }
    }
    // 优惠金额 去除checkbox字段值
    if ("specialDiscountCheckbox" in params) {
      delete params.specialDiscountCheckbox
    }
    // 领取限制
    if ('limitRadio' in params) {
      if (params.limitRadio === -1) {
        params.exchangeDays = -1
        params.exchangeCount = -1
      }
      if (params.limitRadio === 2) {
        params.exchangeCount = params.exchangeCountOne
        delete params.exchangeCountOne
      }
      if (params.limitRadio === 3) {
        params.exchangeCount = params.exchangeCountTwo
        delete params.exchangeCountTwo
      }
      delete params.limitRadio
    }
    // 商品
    if ('category' in params) {
      if (params.category === 1) {
        params.dataType = {
          category: params.category,
          classifyTypeList: params.goodsCategory
        }
        delete params.goodsCategory
      }
      if (params.category === 3) {
        params.dataType = {
          category: params.category,
          brands: params.goodsBrand
        }
        delete params.goodsBrand
      }
      if (params.category === 4) {
        params.dataType = {
          category: params.category,
          goodsInfos: params.goodsInfoList
        }
        delete params.goodsInfoList
      }
      delete params.category
    }

    if (mode === 'edit') {
      // params.cdkeyNum = params.cdkeyNum - dataSource.cdkeyNum
      params.cdkeyOldNumber = dataSource.cdkeyNum
    }
    console.log(params)
    if (mode === 'create') {
      let res = await apiAppCouponInfoAdd({
        ...params,
      })
      if (res.code === 0 && res.data) {
        React.$message({
          type: 'info',
          content: '新建成功'
        })
        this.setState({
          btnLoading: false
        })
        this.props.history.goBack()
      } else {
        this.setState({
          btnLoading: false
        })
      }
    }
    if (mode === 'edit') {
      let res = await apiAppCouponInfoEdit({
        ...params,
        couponId
      })
      if (res.code === 0 && res.data) {
        React.$message({
          type: 'info',
          content: '修改成功'
        })
        this.setState({
          btnLoading: false
        })
        this.props.history.goBack()
      } else {
        this.setState({
          btnLoading: false
        })
      }
    }
  }
  // 表单字段值更新时触发回调事件
  onValuesChange = (changedValues, allValues) => {
    console.log(changedValues)
    // 券类型 与 优惠内容联动
    if ('couponType' in changedValues) {
      this.formRef.resetFields(["couponPrice"])
    }
    // 处理商品范围依赖业务类型字段值问题
    if ('couponSpecies' in changedValues) {
      this.formRef.resetFields(["commodityScope"])
    }
    // 发放总量 选择交互判断
    if ('number' in changedValues) {
      if (changedValues.number === -1) {
        this.formRef.resetFields(["couponStockCount"])
      }
    }
    // 商品范围 优惠叠加交互
    if ('commodityScope' in changedValues) {
      if (changedValues.commodityScope === 2) {
        this.formRef.setFieldsValue({ activitySatisfy: 1 })
      } else {
        this.formRef.setFieldsValue({ activitySatisfy: 0 })
      }
    }
    // 使用门槛 选择交互判断
    if ('usePrice' in changedValues) {
      if (changedValues.usePrice === -1) {
        this.formRef.resetFields(["usePriceNumber"])
      }
    }
    // 优惠内容 是否选择最大折扣金额
    if ('specialDiscountCheckbox' in changedValues) {
      if (changedValues.specialDiscountCheckbox === 'no') {
        this.formRef.resetFields(["couponMaxPrice"])
      }
    }
    // 活动时间 选择交互判断
    if ('activityTime' in changedValues) {
      if (changedValues.activityTime === 0) {
        this.formRef.resetFields(["activityTimeFixed"])
      }
    }
    // 当券有效期为指定时间 活动时间如更改 初始化有效期
    if ("activityTimeFixed" in changedValues) {
      this.formRef.resetFields(["expiryDateAppoint"])
    }
    // 券有效期 选择交互判断
    if ('timeType' in changedValues) {
      if (changedValues.timeType === 0) {
        this.formRef.resetFields([
          "effectiveTimeTwo", "effectiveTimeOne", "takeEffectTime"
        ])
      } else if (changedValues.timeType === 1) {
        this.formRef.resetFields([
          "expiryDateAppoint", "effectiveTimeTwo", "takeEffectTime"
        ])
      } else if (changedValues.timeType === 2) {
        this.formRef.resetFields([
          "expiryDateAppoint", "effectiveTimeOne"
        ])
      }
    }
    // 商品 选择交互判断
    if ('category' in changedValues) {
      if (changedValues.category === 1) {
        this.formRef.resetFields(["goodsBrand", "goodsInfoList"])
        this.GoodsRef.current.resetData()
      } else if (changedValues.category === 3) {
        this.formRef.resetFields(["goodsCategory", "goodsInfoList"])
        this.GoodsRef.current.resetData()
      } else if (changedValues.category === 4) {
        this.formRef.resetFields(["goodsCategory", "goodsBrand"])
      }
    }
    // 限领张数 选择交互判断
    if ('limitRadio' in changedValues) {
      if (changedValues.limitRadio === -1) {
        this.formRef.resetFields(["exchangeCountOne", "exchangeDays", "exchangeCountTwo"])
      } else if (changedValues.limitRadio === 2) {
        this.formRef.resetFields(["exchangeDays", "exchangeCountTwo"])
      } else if (changedValues.limitRadio === 3) {
        this.formRef.resetFields(["exchangeCountOne"])
      }
    }
    // 发放方式 选择交互判断
    if ('cdkeyState' in changedValues) {
      if (changedValues.cdkeyState === 1) {
        this.formRef.resetFields(["cdkeyNum"])
      }
    }
    if ('passwordState' in changedValues) {
      if (changedValues.passwordState === 1) {
        this.formRef.resetFields(["password", "passwordNum"])
      }
    }
    // 是否开启到期提醒
    if ('remindUser' in changedValues) {
      this.formRef.setFieldsValue({
        "remindNumber": !changedValues.remindUser ? null : 1
      })

      console.log(changedValues, 1234);

    }
  }
  // Radio inputNumber 通用赋值方法
  radioInputChange = (e, key) => {
    let { inputDefaultValue } = this.state
    inputDefaultValue[key] = e
    // console.log(e,key)
    this.setState({
      inputDefaultValue
    })
  }
  // 选择商品
  goChoose = () => {
    // console.log(this.GoodsRef)
    this.GoodsRef.current.goChoose()
  }
  // 类目树
  getGoodsClassifyTreeAll = async () => {
    const res = await apiGetGoodsClassifyTreeAll()
    if (res.code === 0) {
      this.setState({
        classifyTree: this.matterTree(res.data)
      })
    }
  }
  matterTree = (data) => {
    data.map((item, index) => {
      if (this.state.selectClassifyKeys.includes(item.value)) {
        item.disabled = true
      }
      if (item.children && item.children.length > 0) {
        this.matterTree(item.children)
      }
    })
    return data
  }
  // 品牌列表
  getBrandList = async () => {
    const res = await apiGetBrandinfoList()
    if (res.code === 0) {
      this.setState({
        brandList: res.data.map((v) => {
          return {
            value: v.brandId,
            label: v.brandName,
            disabled: this.state.selectBrandKeys.includes(v.brandId)
          }
        }),
      })
    }
  }
  goodsListSetData = (e) => {
    this.formRef.setFieldsValue({
      goodsInfoList: e,
    })
  }
  // 阻止级联选择冒泡事件
  clickCascader = (e) => {
    e.preventDefault();
  }
  // 可领时间 禁止选择当天之前时间
  range = (start, end) => {
    const result = [];
    for (let i = start; i <= end; i++) {
      result.push(i);
    }
    return result;
  };
  disabledDate = (current, partial) => {
    // 禁止选择活动结束时间之后
    let { activityTime, activityTimeFixed } = this.formRef.getFieldsValue()
    if (activityTime && activityTimeFixed && expiryDateStartStatus) {
      return current.isAfter(activityTimeFixed[1])
    }
  };
  disabledDateTime = (current, partial) => {
    // 当为开始时间时disabledDate做禁止(天)校验
    if (partial === 'start') {
      expiryDateStartStatus = true
    } else {
      expiryDateStartStatus = false
    }
    // 时分禁止校验
    let { activityTime, activityTimeFixed } = this.formRef.getFieldsValue()
    if (activityTime && activityTimeFixed) {
      let hour = moment(activityTimeFixed[1]).hour()
      let minutes = moment(activityTimeFixed[1]).minutes()
      if (current && moment(current).date() === moment(activityTimeFixed[1]).date() && partial === 'start') {
        return {
          disabledHours: () => this.range(hour, 23).slice(1),
          disabledMinutes: () => this.range(minutes, 59)
        };
      }
    }
  };
  reset(values) {
    this.formRef.resetFields()
    let couponSourceCard = 0
    if(values.target.value === 'M') {
      couponSourceCard = 1
    }
    this.formRef.setFieldsValue({
      couponSpecies: values.target.value,
      couponSourceCard
    })
  }

  render() {
    let {
      mode,
      goodsDefault,
      selectGoodsKeys,
      initialValues,
      brandList,
      btnLoading,
      classifyTree,
      dataSource
    } = this.state
    let title = ''
    switch (mode) {
      case "create":
        title = "新建优惠券"
        break;
      case "view":
        title = "查看优惠券"
        break;
      case "edit":
        title = "修改优惠券"
    }
    return (
      <div className="commodity-list-detail p-layout-box">
        <GoBack history={this.props.history} title={title} />

        <Form
          onFinish={this.onFinish}
          ref={ref => this.formRef = ref}
          labelCol={{
            span: 2,
          }}
          wrapperCol={{
            span: 20,
          }}
          onFinishFailed={this.onFinishFailed}
          onValuesChange={this.onValuesChange}
          initialValues={initialValues}
        >
          <Title level={4} style={{ margin: "10px 0 0 60px" }}>基础设置</Title>
          <Form.Item rules={[{ required: true }]} label="业务类型" name="couponSpecies">
            <Radio.Group disabled={mode === 'edit' || mode === 'view'} onChange={(value) => this.reset(value)}>
              <Radio value={"P"}>线上商城</Radio>
              <Radio value={"M"}>门店服务</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item rules={[{ required: true }]} label="券名称" name="couponTitle">
            <Input disabled={mode === 'edit' || mode === 'view'} allowClear style={{ width: 300 }}
              maxLength={30} showCount />
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.couponSpecies !== currentValues.couponSpecies}
          >
            {({ getFieldValue }) =>
              <Form.Item rules={[{ required: true }]} label="券类型" name="couponType">
                {
                  getFieldValue('couponSpecies') === 'P' ?
                    <Select style={{ width: 300 }} disabled={mode === 'edit' || mode === 'view'}>
                      <Option value="J">代金券</Option>
                      <Option value="Z">折扣券</Option>
                    </Select>
                    : <Select style={{ width: 300 }} disabled>
                      <Option value="J">代金券</Option>
                    </Select>
                }
              </Form.Item>
            }
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.couponSpecies !== currentValues.couponSpecies}
          >
            {({ getFieldValue }) =>
              <Form.Item
                label="商品范围"
                name="commodityScope"
                rules={[
                  {
                    required: true,
                  },
                ]}
              >
                {
                  getFieldValue('couponSpecies') === 'P' ?
                    <Select style={{ width: 300 }} disabled={mode === 'edit' || mode === 'view'}>
                      <Option value={0}>全部商品可用</Option>
                      <Option value={1}>限制品类可用</Option>
                      <Option value={2}>商品券</Option>
                    </Select> : <Select style={{ width: 300 }} disabled>
                      <Option value={0}>全部商品可用</Option>
                    </Select>
                }
              </Form.Item>
            }
          </Form.Item>
          <Form.Item label="发放总量" name="number" rules={[{ required: true }]}>
            <Radio.Group disabled={mode === 'view'}>
              <Radio value={-1}>不限</Radio>
              <Radio value={2}>
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, currentValues) => prevValues.number !== currentValues.number}
                >
                  {({ getFieldValue }) => {
                    return <>
                      <span className="ant-form-text">共</span>
                      <Form.Item name="couponStockCount" noStyle
                        rules={[{
                          required: getFieldValue('number') !== -1,
                          message: '请输入发放总量'
                        }, {
                          min: (mode === 'edit' && (dataSource.couponStockCount - dataSource.couponStock !== 0)) ? (dataSource.couponStockCount - dataSource.couponStock) : 1,
                          type: "number",
                          message: `已发放给消费者${dataSource.couponStockCount - dataSource.couponStock}张，不可低于该值!`
                        }]}>
                        <InputNumber
                          precision={0}
                          min={1}
                          max={999999}
                          disabled={getFieldValue('number') === -1 || mode === 'view'}
                          style={{ width: 100 }}
                        />
                      </Form.Item>
                      <span className="ant-form-text">张</span>
                      {mode === 'edit' && dataSource.couponStock !== -1 ? <span
                        className="ant-form-text ext">(剩余库存{dataSource.couponStock}张)</span> : null}
                    </>
                  }}
                </Form.Item>
              </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="使用门槛" name="usePrice" rules={[{ required: true }]}>
            <Radio.Group disabled={mode === 'edit' || mode === 'view'}>
              <Radio value={-1}>不限</Radio>
              <Radio value={2}>
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, currentValues) => prevValues.usePrice !== currentValues.usePrice}
                >
                  {({ getFieldValue }) => {
                    return <>
                      <span className="ant-form-text">满</span>
                      <Form.Item name="usePriceNumber" noStyle
                        rules={[{
                          required: getFieldValue('usePrice') !== -1,
                          message: '请输入门槛金额'
                        }]}
                        getValueProps={v => ({ value: v / 100, v })}
                        getValueFromEvent={e => e ? e * 100 : e}
                      >
                        <InputNumber
                          precision={2}
                          min={0.01}
                          max={99999}
                          disabled={getFieldValue('usePrice') === -1 || mode === 'view' || mode === 'edit'}
                          style={{ width: 100 }}
                        />
                      </Form.Item>
                      <span className="ant-form-text">可用</span>
                    </>
                  }}
                </Form.Item>
              </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="优惠内容"
            rules={[{ required: true }]}
            shouldUpdate={(prevValues, currentValues) => prevValues.couponType !== currentValues.couponType}
          >
            {({ getFieldValue }) => <>
              {
                getFieldValue('couponType') === "J" ? (
                  <>
                    <span className="ant-form-text">减免</span>
                    <Form.Item name="couponPrice" noStyle
                      rules={[
                        {
                          required: true,
                          message: '请输入优惠内容'
                        },
                        // {
                        //     max: 99900,
                        //     type: "number",
                        //     message: `1!`
                        // }, {
                        //     min: 100,
                        //     type: "number",
                        //     message: `2!`
                        // }
                      ]}
                      getValueProps={v => ({ value: v / 100, v })}
                      getValueFromEvent={e => e ? e * 100 : e}
                    >
                      <InputNumber
                        precision={0}
                        min={1}
                        max={999}
                        placeholder="请输入1~999整数"
                        style={{ width: 150 }}
                        disabled={mode === 'edit' || mode === 'view'}
                      />
                    </Form.Item>
                    <span className="ant-form-text">元</span>
                  </>
                ) : null
              }
              {
                getFieldValue('couponType') === "Z" ? (
                  <Space direction="vertical">
                    <div>
                      <span className="ant-form-text">打</span>
                      <Form.Item name={'couponPrice'} noStyle
                        rules={[{ required: true, message: '请输入折扣' }]}
                        getValueProps={v => ({ value: v / 10, v })}
                        getValueFromEvent={e => e ? e * 10 : e}
                      >
                        <InputNumber
                          precision={1}
                          min={0.1}
                          max={9.9}
                          style={{ width: 100 }}
                          disabled={mode === 'edit' || mode === 'view'}
                        />
                      </Form.Item>
                      <span className="ant-form-text">折</span>
                    </div>
                    <div>
                      <Form.Item name={'specialDiscountCheckbox'} noStyle
                        getValueProps={value => ({ checked: value === 'yes', value })}
                        getValueFromEvent={e => e.target.checked ? 'yes' : 'no'}
                      >
                        <Checkbox disabled={mode === 'edit' || mode === 'view'}
                          className={"item-lh"}>最大折扣金额:</Checkbox>
                      </Form.Item>
                      <Form.Item name={'couponMaxPrice'} noStyle
                        rules={[{
                          required: getFieldValue('specialDiscountCheckbox') === "yes",
                          message: '请输入折扣金额'
                        }]}
                        getValueProps={v => ({ value: v / 100, v })}
                        getValueFromEvent={e => e ? e * 100 : e}
                      >
                        <InputNumber
                          precision={0}
                          min={1}
                          max={999}
                          style={{ width: 100 }}
                          disabled={getFieldValue('specialDiscountCheckbox') !== "yes" || mode === 'edit' || mode === 'view'}
                        />
                      </Form.Item>
                      <span className="ant-form-text">元</span>
                    </div>
                  </Space>
                ) : null
              }
            </>}
          </Form.Item>
          <Form.Item label="活动时间" name="activityTime" rules={[{ required: true }]}>
            <Radio.Group disabled={mode === 'edit' || mode === 'view'}>
              <Radio value={0}>长期</Radio>
              <Radio value={1}>
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, currentValues) => prevValues.activityTime !== currentValues.activityTime}
                >
                  {({ getFieldValue }) => {
                    return <>
                      <span className="ant-form-text">固定时间</span>
                      <Form.Item name="activityTimeFixed" noStyle
                        rules={[{
                          required: getFieldValue('activityTime') !== 0,
                          message: '请选择固定时间'
                        }]}
                        getValueProps={v => ({
                          value: v ? [moment(v[0]), moment(v[1])] : null,
                          v
                        })}
                        getValueFromEvent={e => e ? [moment(e[0]).format('YYYY-MM-DD HH:mm'), moment(e[1]).format('YYYY-MM-DD HH:mm')] : e}
                      >
                        <RangePicker
                          ranges={{
                            "今天": [moment(), moment()],
                            '本周': [moment().startOf('week'), moment().endOf('week')],
                          }}
                          showTime={{
                            format: 'HH:mm',
                          }}
                          format="YYYY-MM-DD HH:mm"
                          style={{ width: 350 }}
                          disabled={getFieldValue('activityTime') === 0 || mode === 'view' || mode === 'edit'}
                        />
                      </Form.Item>
                    </>
                  }}
                </Form.Item>
              </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="可领时间" name="receiveTime"
            rules={[{ required: true, message: '请选择可领时间' }]}
            getValueProps={v => ({ value: v ? moment(v) : null, v })}
            getValueFromEvent={e => e ? moment(e).format('YYYY-MM-DD HH:mm') : e}
          >
            <DatePicker
              disabled={mode === 'edit' || mode === 'view'}
              showTime={{
                format: 'HH:mm',
              }}
              format="YYYY-MM-DD HH:mm"
              style={{ width: 200 }}
            />
          </Form.Item>
          <Form.Item label="券有效期" name="timeType" rules={[{ required: true, message: "请选择券有效期" }]}>
            <Radio.Group disabled={mode === 'edit' || mode === 'view'}>
              <Space direction="vertical">
                <Radio value={0}>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.timeType !== currentValues.timeType}
                  >
                    {({ getFieldValue }) => {
                      return <div style={{ display: "flex", alignItems: "baseline" }}>
                        <span className="ant-form-text">指定日期</span>
                        <Form.Item name="expiryDateAppoint"
                          rules={[{
                            required: getFieldValue('timeType') === 0,
                            message: '请选择指定日期'
                          }]}
                          getValueProps={v => ({
                            value: v ? [moment(v[0]), moment(v[1])] : null,
                            v
                          })}
                          getValueFromEvent={e => e ? [moment(e[0]).format('YYYY-MM-DD HH:mm'), moment(e[1]).format('YYYY-MM-DD HH:mm')] : e}
                          style={{ marginBottom: 0 }}
                        >
                          <RangePicker
                            showTime={{
                              // format: 'HH:mm',
                              defaultValue: [moment('00:00', 'HH:mm'), moment('00:00', 'HH:mm')],
                            }}
                            format="YYYY-MM-DD HH:mm"
                            style={{ width: 350 }}
                            disabled={getFieldValue('timeType') !== 0 || mode === 'view' || mode === 'edit'}
                            disabledDate={this.disabledDate}
                            disabledTime={this.disabledDateTime}
                          />
                        </Form.Item>
                      </div>
                    }}
                  </Form.Item>
                </Radio>
                <Radio value={1}>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.timeType !== currentValues.timeType}
                  >
                    {({ getFieldValue }) => {
                      return <div style={{ display: "flex", alignItems: "baseline" }}>
                        <span className="ant-form-text">领券后</span>
                        <Form.Item name="effectiveTimeOne"
                          rules={[{
                            required: getFieldValue('timeType') === 1,
                            message: '请输入天数'
                          }]}
                          style={{ marginBottom: 0 }}
                        >
                          <InputNumber
                            precision={0}
                            min={1}
                            max={7300}
                            style={{ width: 100, marginRight: 7 }}
                            disabled={getFieldValue('timeType') !== 1 || mode === 'view' || mode === 'edit'}
                          />
                        </Form.Item>
                        <span className="ant-form-text">天内可用</span>
                      </div>
                    }}
                  </Form.Item>
                </Radio>
                <Radio value={2}>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.timeType !== currentValues.timeType}
                  >
                    {({ getFieldValue }) => {
                      return <div style={{ display: "flex", alignItems: "baseline" }}>
                        <span className="ant-form-text">领券后</span>
                        <Form.Item name="takeEffectTime"
                          rules={[{
                            required: getFieldValue('timeType') === 2,
                            message: '请输入天数'
                          }]}
                          style={{ marginBottom: 0 }}
                        >
                          <InputNumber
                            precision={0}
                            min={1}
                            max={7300}
                            style={{ width: 100, marginRight: 7 }}
                            disabled={getFieldValue('timeType') !== 2 || mode === 'view' || mode === 'edit'}
                          />
                        </Form.Item>
                        <span className="ant-form-text">天后生效，</span>
                        <Form.Item name="effectiveTimeTwo"
                          rules={[{
                            required: getFieldValue('timeType') === 2,
                            message: '请输入天数'
                          }]}
                          style={{ marginBottom: 0 }}
                        >
                          <InputNumber
                            precision={0}
                            min={1}
                            max={7300}
                            style={{ width: 100, marginRight: 7 }}
                            disabled={getFieldValue('timeType') !== 2 || mode === 'view' || mode === 'edit'}
                          />
                        </Form.Item>
                        <span className="ant-form-text">天内可用</span>
                      </div>
                    }}
                  </Form.Item>
                </Radio>
              </Space>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.commodityScope !== currentValues.commodityScope}
          >
            {({ getFieldValue }) => <>
              {
                getFieldValue('commodityScope') === 1 ? (
                  <Form.Item label="商品" name="category" rules={[{
                    required: true,
                    message: '请选择对应分类及内容'
                  }]}>
                    <Radio.Group style={{ width: "100%" }}
                      disabled={mode === 'view' || mode === 'edit'}>
                      <Space direction="vertical">
                        <Radio value={1}>
                          <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.category !== currentValues.category}
                          >
                            {({ getFieldValue }) => {
                              return <div
                                style={{
                                  display: "flex",
                                  alignItems: "baseline",
                                  position: 'relative'
                                }} id="area">
                                <span className="ant-form-text">类目</span>
                                <Form.Item name="goodsCategory"
                                  rules={[{
                                    required: getFieldValue('category') === 1,
                                    message: '请选择商品类目'
                                  }]}
                                  style={{ width: "350px", marginBottom: 0 }}
                                >
                                  <TreeSelect
                                    getPopupContainer={() => document.getElementById('area')}
                                    placeholder="请选择商品类目"
                                    onClick={this.clickCascader}
                                    treeData={classifyTree}
                                    disabled={getFieldValue('category') !== 1 || mode === 'view'}
                                    treeCheckable={true}
                                  />
                                </Form.Item>
                              </div>
                            }}
                          </Form.Item>
                        </Radio>
                        <Radio value={3}>
                          <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.category !== currentValues.category}
                          >
                            {({ getFieldValue }) => {
                              return <div
                                style={{ display: "flex", alignItems: "baseline" }}>
                                <span className="ant-form-text">品牌</span>
                                <Form.Item name="goodsBrand"
                                  rules={[{
                                    required: getFieldValue('category') === 3,
                                    message: '请选择商品品牌'
                                  }]}
                                  style={{ width: "350px", marginBottom: 0 }}
                                >
                                  <Select
                                    showSearch
                                    mode="multiple"
                                    disabled={getFieldValue('category') !== 3 || mode === 'view'}
                                    options={brandList}
                                    filterOption={(input, option) =>
                                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                    }
                                    placeholder="请选择商品品牌"
                                    onClick={this.clickCascader}
                                  />
                                </Form.Item>
                              </div>
                            }}
                          </Form.Item>
                        </Radio>
                        <Radio value={4}>
                          <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, currentValues) => prevValues.category !== currentValues.category}
                          >
                            {({ getFieldValue }) => {
                              return <div
                                style={{ display: "flex", alignItems: "baseline" }}>
                                <span className="ant-form-text">部分商品</span>
                                <Form.Item name="goodsInfoList"
                                  rules={[{
                                    required: getFieldValue('category') === 4,
                                    message: '请选择商品'
                                  }]}
                                  style={{ width: "350px" }}
                                >
                                  <TheButton type="default" size="middle"
                                    disabled={getFieldValue('category') !== 4 || mode === 'view'}
                                    onClick={() => this.goChoose()}>选择商品</TheButton>
                                </Form.Item>
                              </div>
                            }}
                          </Form.Item>
                        </Radio>
                      </Space>
                      <Goods ref={this.GoodsRef} mode={mode}
                        initData={goodsDefault}
                        disabledKeys={selectGoodsKeys}
                        setData={(data) => this.goodsListSetData(data)}
                        getFieldsValue={(key, isCheck) => this.getFieldsValue(key, isCheck)}></Goods>
                    </Radio.Group>
                  </Form.Item>
                ) : null
              }
              {
                getFieldValue('commodityScope') === 2 ? (
                  <Form.Item label={<div className={"form-item-required"}>商品</div>} name="category">
                    <div style={{ display: "flex", alignItems: "baseline" }}>
                      {/*<span className="ant-form-text">品牌</span>*/}
                      <Form.Item name="goodsInfoList"
                        rules={[{
                          required: true,
                          message: '请选择商品'
                        }]}
                        style={{ width: "350px" }}
                      >
                        <TheButton type="default" size="middle" disabled={mode !== 'create'}
                          onClick={() => this.goChoose()}>选择商品</TheButton>
                      </Form.Item>
                    </div>
                    <Goods ref={this.GoodsRef} mode={mode}
                      initData={goodsDefault}
                      type={'radio'} disabledKeys={selectGoodsKeys}
                      setData={(data) => this.goodsListSetData(data)}
                      getFieldsValue={(key, isCheck) => this.getFieldsValue(key, isCheck)}></Goods>
                  </Form.Item>
                ) : null
              }
            </>}
          </Form.Item>
          <Title level={4} style={{ margin: "10px 0 0 60px" }}>其他设置</Title>
          <Form.Item label="限领张数" name="limitRadio" rules={[{ required: true, message: "请选择限领方式" }]}>
            <Radio.Group disabled={mode === 'view'}>
              <Space direction="vertical">
                <Radio value={-1} className={"item-lh"}>不限</Radio>
                <Radio value={2}>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.limitRadio !== currentValues.limitRadio}
                  >
                    {({ getFieldValue }) => {
                      return <div style={{ display: "flex", alignItems: "baseline" }}>
                        <span className="ant-form-text">每人限领</span>
                        <Form.Item name="exchangeCountOne"
                          rules={[{
                            required: getFieldValue('limitRadio') === 2,
                            message: '请输入张数'
                          }]}
                          style={{ marginBottom: 0 }}
                        >
                          <InputNumber
                            precision={0}
                            min={1}
                            max={9}
                            style={{ width: 100, marginRight: 7 }}
                            disabled={getFieldValue('limitRadio') !== 2 || mode === 'view'}
                          />
                        </Form.Item>
                        <span className="ant-form-text">张</span>
                      </div>
                    }}
                  </Form.Item>
                </Radio>
                <Radio value={3}>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.limitRadio !== currentValues.limitRadio}
                  >
                    {({ getFieldValue }) => {
                      return <div style={{ display: "flex", alignItems: "baseline" }}>
                        <span className="ant-form-text">每人每</span>
                        <Form.Item name="exchangeDays"
                          rules={[{
                            required: getFieldValue('limitRadio') === 3,
                            message: '请输入天数'
                          }]}
                          style={{ marginBottom: 0 }}
                        >
                          <InputNumber
                            precision={0}
                            min={1}
                            max={7300}
                            style={{ width: 100, marginRight: 7 }}
                            disabled={getFieldValue('limitRadio') !== 3 || mode === 'view'}
                          />
                        </Form.Item>
                        <span className="ant-form-text">日，限领</span>
                        <Form.Item name="exchangeCountTwo"
                          rules={[{
                            required: getFieldValue('limitRadio') === 3,
                            message: '请输入张数'
                          }]}
                          style={{ marginBottom: 0 }}
                        >
                          <InputNumber
                            precision={0}
                            min={1}
                            max={9}
                            style={{ width: 100, marginRight: 7 }}
                            disabled={getFieldValue('limitRadio') !== 3 || mode === 'view'}
                          />
                        </Form.Item>
                        <span className="ant-form-text">张</span>
                      </div>
                    }}
                  </Form.Item>
                </Radio>
              </Space>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.couponSpecies !== currentValues.couponSpecies}
          >
            {({ getFieldValue }) =>
              <Form.Item label="发放方式">
                {
                  getFieldValue('couponSpecies') === 'P' ?
                    <Row>
                      <Col span={24}>
                        <Form.Item name={'couponSourceDirect'} noStyle
                          getValueProps={value => ({ checked: value === 1, value })}
                          getValueFromEvent={e => e.target.checked ? 1 : 0}
                        >
                          <Checkbox className={"item-lh"} disabled={mode === 'view'}>
                            可直接领取
                            {/*<span className={"ext"}>取消勾选后，将不在商品详情页、购物车、领券中心显示优惠券，且不会在详情页、购物车自动领券</span>*/}
                          </Checkbox>
                        </Form.Item>
                      </Col>
                      <Col span={24}>
                        <Form.Item name={'cdkeyState'} noStyle
                          getValueProps={value => ({ checked: value === 0, value })}
                          getValueFromEvent={e => e.target.checked ? 0 : 1}
                        >
                          <Checkbox className={"item-lh"}
                            disabled={mode === 'view' || (mode === 'edit' && dataSource.cdkeyState === 0)}>
                            <Form.Item
                              noStyle
                              shouldUpdate
                            >
                              {({ getFieldValue }) => {
                                let value = getFieldValue('cdkeyState') !== 0 || mode === 'view'
                                let total = getFieldValue('couponStockCount') ?? Infinity;
                                let cdk = getFieldValue('cdkeyNum') ?? 0;
                                return <div style={{ display: "flex", alignItems: "baseline" }}>
                                  <span className="ant-form-text">CDK关联</span>
                                  <span className="ant-form-text">发放数量</span>
                                  <Form.Item name="cdkeyNum"
                                    dependencies={['couponStockCount']}
                                    rules={[{
                                      required: !value,
                                      message: '请输入数量'
                                    }, {
                                      max: total,
                                      type: "number",
                                      message: `数量高于优惠券总库存数量${cdk - total}张!`
                                    }, {
                                      min: (mode === 'edit' && dataSource.cdkeyNum !== -1) ? dataSource.cdkeyNum : 0,
                                      type: "number",
                                      message: `CDK数量只能新增!`
                                    }]}
                                    style={{ marginBottom: 0 }}
                                  >
                                    <InputNumber
                                      precision={0}
                                      // min={0}
                                      style={{ width: 100, marginRight: 7 }}
                                      disabled={value}
                                    />
                                  </Form.Item>
                                </div>
                              }}
                            </Form.Item>
                          </Checkbox>
                        </Form.Item>
                      </Col>
                      <Col span={24}>
                        <Form.Item name={'passwordState'} noStyle
                          getValueProps={value => ({ checked: value === 0, value })}
                          getValueFromEvent={e => e.target.checked ? 0 : 1}
                        >
                          <Checkbox className={"item-lh"}
                            disabled={mode === 'view' || (mode === 'edit' && dataSource.passwordState === 0)}>
                            <Form.Item
                              noStyle
                              shouldUpdate
                            >
                              {({ getFieldValue }) => {
                                let value = getFieldValue('passwordState') !== 0 || mode === 'view'
                                let total = getFieldValue('couponStockCount') ?? Infinity;
                                let command = getFieldValue('passwordNum') ?? 0;
                                return <div style={{ display: "flex", alignItems: "baseline" }}>
                                  <span className="ant-form-text">口令关联</span>
                                  <span className="ant-form-text">口令</span>
                                  <Form.Item name="password"
                                    rules={[{
                                      required: !value,
                                      message: '请输入口令'
                                    }]}
                                    style={{ marginBottom: 0 }}
                                  >
                                    <Input
                                      style={{ width: 100, marginRight: 7 }}
                                      disabled={value}
                                    />
                                  </Form.Item>
                                  <span className="ant-form-text">发放数量</span>
                                  <Form.Item name="passwordNum"
                                    dependencies={['couponStockCount']}
                                    rules={[{
                                      required: !value,
                                      message: '请输入数量'
                                    }, {
                                      max: total,
                                      type: "number",
                                      message: `数量高于优惠券总库存数量${command - total}张!`
                                    }, {
                                      min: (mode === 'edit' && dataSource.passwordNum !== -1) ? dataSource.cdkeyNum : 0,
                                      type: "number",
                                      message: `不能低于口令已兑换的张数!`
                                    }]}
                                    style={{ marginBottom: 0 }}
                                  >
                                    <InputNumber
                                      precision={0}
                                      min={1}
                                      style={{ width: 100, marginRight: 7 }}
                                      disabled={value}
                                    />
                                  </Form.Item>
                                </div>
                              }}
                            </Form.Item>
                          </Checkbox>
                        </Form.Item>
                      </Col>
                      <Col span={24}>
                        <Form.Item name={'couponSourceRegister'} noStyle
                          getValueProps={value => ({ checked: value === 1, value })}
                          getValueFromEvent={e => e.target.checked ? 1 : 0}
                        >
                          <Checkbox className={"item-lh"} disabled={mode === 'view'}>
                            注册赠送
                          </Checkbox>
                        </Form.Item>
                      </Col>
                      <Col span={24}>
                        <Form.Item name={'couponSourceShare'} noStyle
                          getValueProps={value => ({ checked: value === 1, value })}
                          getValueFromEvent={e => e.target.checked ? 1 : 0}
                        >
                          <Checkbox className={"item-lh"} disabled={mode === 'view'}>
                            分享成功赠送
                          </Checkbox>
                        </Form.Item>
                      </Col>
                      <Col span={24}>
                        <Form.Item name={'couponSourceCard'} noStyle
                          getValueProps={value => ({ checked: value === 1, value })}
                          getValueFromEvent={e => e.target.checked ? 1 : 0}
                        >
                          <Checkbox className={"item-lh"} disabled={mode === 'view'}>
                            绑定会员卡类型，购买该卡后发放
                          </Checkbox>
                        </Form.Item>
                      </Col>
                    </Row>
                    : <Form.Item name={'couponSourceCard'} noStyle
                      getValueProps={value => ({ checked: value === 1, value })}
                      getValueFromEvent={e => e.target.checked ? 1 : 0}
                    >
                      <Checkbox className={"item-lh"} disabled={mode === 'view'}>
                        绑定会员卡类型，购买该卡后发放
                      </Checkbox>
                    </Form.Item>
                }
              </Form.Item>
            }
          </Form.Item>
          <Form.Item noStyle shouldUpdate>
            {({ getFieldValue }) => {
              return <>
                {getFieldValue('couponSpecies') === 'P' ?
                  <>
                    <Form.Item label="到期提醒" shouldUpdate>
                      {({ getFieldValue }) => {
                        return <Space>
                          <Form.Item name={'remindUser'} noStyle
                            getValueProps={value => ({ checked: value === 1, value })}
                            getValueFromEvent={e => e.target.checked ? 1 : 0}
                          >
                            <Checkbox className={"item-lh"} disabled={mode === 'view'}>提前</Checkbox>
                          </Form.Item>
                          <Form.Item name={'remindNumber'} noStyle
                            rules={[{
                              required: getFieldValue('remindUser') === 1,
                              message: '请选择天数'
                            }]}>
                            <Select style={{ width: 80 }}
                              disabled={getFieldValue('remindUser') !== 1 || mode === 'view'}>
                              <Option value="1">1</Option>
                              <Option value="2">2</Option>
                              <Option value="3">3</Option>
                              <Option value="4">4</Option>
                              <Option value="5">5</Option>
                            </Select>
                          </Form.Item>
                          <span className="ant-form-text">天提醒用户</span>
                        </Space>
                      }}
                    </Form.Item>
                    <Form.Item label="优惠叠加"
                      shouldUpdate={(prevValues, currentValues) => prevValues.commodityScope !== currentValues.commodityScope}
                    >
                      {({ getFieldValue }) => {
                        return <Row>
                          <Col span={2}>
                            <Form.Item name={'activityNewPerson'} noStyle
                              getValueProps={value => ({ checked: value === 1, value })}
                              getValueFromEvent={e => e.target.checked ? 1 : 0}
                            >
                              <Checkbox className={"item-lh"} disabled>新人活动</Checkbox>
                            </Form.Item>
                          </Col>
                          <Col span={2}>
                            <Form.Item name={'activitySeckill'} noStyle
                              getValueProps={value => ({ checked: value === 1, value })}
                              getValueFromEvent={e => e.target.checked ? 1 : 0}
                            >
                              <Checkbox className={"item-lh"} disabled>秒杀</Checkbox>
                            </Form.Item>
                          </Col>
                          <Col span={2}>
                            <Form.Item name={'activitySpecial'} noStyle
                              getValueProps={value => ({ checked: value === 1, value })}
                              getValueFromEvent={e => e.target.checked ? 1 : 0}
                            >
                              <Checkbox className={"item-lh"} disabled={mode === 'view'}>特惠</Checkbox>
                            </Form.Item>
                          </Col>
                          <Col span={2}>
                            <Form.Item name={'activitySatisfy'} noStyle
                              getValueProps={value => ({ checked: value === 1, value })}
                              getValueFromEvent={e => e.target.checked ? 1 : 0}
                            >

                              <Checkbox className={"item-lh"}
                                disabled={getFieldValue('commodityScope') === 0 || getFieldValue('commodityScope') === 1 || mode === 'view' ? true : false}
                              >满减</Checkbox>
                            </Form.Item>
                          </Col>
                          <Col span={2}>
                            <Form.Item name={'activityPresented'} noStyle
                              getValueProps={value => ({ checked: value === 1, value })}
                              getValueFromEvent={e => e.target.checked ? 1 : 0}
                            >
                              <Checkbox className={"item-lh"} disabled>满赠</Checkbox>
                            </Form.Item>
                          </Col>
                        </Row>
                      }}
                    </Form.Item>
                  </>
                  : <></>}
              </>
            }}
          </Form.Item>
          {
            mode === 'view' ? [] : <Form.Item
              wrapperCol={{
                offset: 4,
                span: 16,
              }}

            >
              <Space>
                <Button onClick={() => this.props.history.goBack()}>取消</Button>
                <Button loading={btnLoading} htmlType="submit" type="primary">保存</Button>
              </Space>
            </Form.Item>
          }
        </Form>
      </div>
    );
  }
}

export default Add;
